<?php
// src/Security/ApiKeyUserProvider.php
namespace App\Security;

use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use Monolog\Logger;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

class CertToken
{
    const SING_CHECK_CODE_KEY = "94685c89012e79840b326884cf708c61";//用于校验码的生成;
    private $condition;
    private $logger;
    private $jobConn;

    /**
     * CertToken constructor.
     * @param ContainerInterface $condition
     * @param Logger $logger
     */
    public function __construct($condition, $logger)
    {
        $this->condition = $condition;
        $this->jobConn = $condition->get('doctrine.dbal.customer_connection');
        $this->logger = $logger;
    }

    /**
     * @param Request $request
     * @return array
     */
    public function begin(Request $request)
    {
        $apiKey = $request->headers->get('apiKey');
        if (empty((string) $apiKey)) {
            return array('code' => 400, 'message' => "token不存在");
        }
        $token = (new Parser())->parse((string) $apiKey);
        $data = new ValidationData();
        $data->setIssuer('http://symfony4.cn');
        $data->setAudience('http://symfony4.cn');
        $data->setCurrentTime(time() + 60);
        $data->setId(1);
        $signer = new Sha256();
        if ($token->validate($data) && $token->verify($signer, $this::SING_CHECK_CODE_KEY)) {
            $username = $token->getClaim('username');
            $userId = $token->getClaim('user_id');
            $role = $token->getClaim('role');
        } else {
            return array('code' => 500, 'message' => "token解析失败");
        }

        // Look up the username based on the token in the database, via
        // an API call, or do something entirely different
        return array('code' => 0, "message" => "ok", 'data' => array('username' => $username, 'user_id' => $userId, 'role' => $role));
    }
}